import { ref } from 'vue';

import { deserialize } from '@/plugins/reflect-metadata';
import type { ListState } from '@/types';

import { getAllProductName, getProductName } from '../api';
import { TransNameItem, TransNameList, TransNameQuery } from '../models/TransSelectQuery';

const useProductList = () => {
  const params = ref<TransNameQuery>(new TransNameQuery());
  const state = ref<ListState<TransNameItem>>({
    data: [],
    loading: false,
    total: 0,
  });

  const fetchData = async () => {
    try {
      state.value.loading = true;
      const { data } = await getProductName(params.value);
      const resultData = deserialize(data, TransNameList);
      state.value.data = resultData.items;
      state.value.total = resultData.total;
    } catch (error) {
      //
    } finally {
      state.value.loading = false;
    }
  };

  const stateAll = ref<ListState<TransNameItem>>({
    data: [],
    loading: false,
    total: 0,
  });

  const fetchAllData = async () => {
    try {
      stateAll.value.loading = true;
      const { data } = await getAllProductName(params.value);
      const resultData = deserialize(data, TransNameList);
      stateAll.value.data = resultData.items;
      stateAll.value.total = resultData.total;
    } catch (error) {
      //
    } finally {
      stateAll.value.loading = false;
    }
  };

  return {
    params,
    state,
    stateAll,
    fetchData,
    fetchAllData,
  };
};

export default useProductList;
